package com.youngjun.common.security.service.impl;

import com.youngjun.common.security.service.CaptchaService;
import com.youngjun.common.util.CaptchaUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;

public class DefaultCaptchaServiceImpl implements CaptchaService {

    private static final String CAPTCHA_VALIDATE_CODE_KEY = "CAPTCHA_VALIDATE_CODE";

    @Override
    public void getCode(OutputStream outputStream) {
        try {
            String code = CaptchaUtils.getRandCode();
            getSession(true).setAttribute(CAPTCHA_VALIDATE_CODE_KEY, code);
            CaptchaUtils.getCode(outputStream,code);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HttpSession getSession(boolean create) {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession(create);
    }

    @Override
    public boolean validateCode(String code) {
        HttpSession session = getSession(false);
        try {
            return session != null
                    && session.getAttribute(CAPTCHA_VALIDATE_CODE_KEY) != null
                    && code.toUpperCase().equals(session.getAttribute(CAPTCHA_VALIDATE_CODE_KEY).toString().toUpperCase());
        } finally {
            if (session != null)
                session.removeAttribute(CAPTCHA_VALIDATE_CODE_KEY);
        }
    }
}
